package com.guldan.jaina.manager;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

import com.guldan.core.dic.DicUtils;
import com.guldan.core.enums.UploadTypeEn;
import com.guldan.core.enums.ValidatingRegisterTypeEn;
import com.guldan.core.exception.BusinessException;
import com.guldan.core.utils.MathUtil;
import com.guldan.jaina.dto.dictionary.DictionaryDTO;
import com.guldan.jaina.dto.progress.BarDTO;
import com.guldan.jaina.dto.users.UsersDTO;
import com.guldan.jaina.task.BankReturnUploadThread;
import com.guldan.jaina.task.RegisterUploadThread;
import com.guldan.mapper.db.dto.register.RegisterTempateDTO;
import com.guldan.mapper.db.entity.*;
import com.guldan.mapper.db.entity.Dictionary;
import com.guldan.mapper.db.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guldan.core.constants.CommonConstant;
import com.guldan.core.enums.ProjectRegisterBatchEn;
import com.guldan.core.enums.ProjectRegisterEn;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.area.AreaDTO;
import com.guldan.jaina.dto.area.AreaSearchDTO;
import com.guldan.jaina.dto.orgbatchsummary.OrgBatchSummaryDTO;
import com.guldan.jaina.dto.paysummary.PaySummaryDTO;
import com.guldan.jaina.dto.project.ProjectDTO;
import com.guldan.jaina.dto.project.ProjectSearchDTO;
import com.guldan.jaina.dto.projectextensiondic.ProjectExtensionDicDTO;
import com.guldan.jaina.dto.projectextensiondic.ProjectExtensionDicSearchDTO;
import com.guldan.jaina.dto.projectregisterupload.ProjectRegisterUploadDTO;
import com.guldan.jaina.dto.register.RegisterTemplateDTO;
import com.guldan.jaina.dto.register.RegisterTemplateDataDTO;
import com.guldan.jaina.dto.register.RegisterTemplateSearchDTO;
import com.guldan.jaina.dto.register.RegisterUploadResultDTO;
import com.guldan.jaina.dto.register.summary.SummaryDTO;
import com.guldan.jaina.dto.register.summary.SummaryDetailDTO;
import com.guldan.jaina.dto.register.summary.SummaryFileDTO;
import com.guldan.jaina.dto.registersuccess.RegisterSuccessDTO;
import com.guldan.jaina.dto.registersuccess.RegisterSuccessSearchDTO;
import com.guldan.jaina.utils.UserUtils;

import net.sf.json.JSONArray;

/**
 * Created by Silas.
 * Date: 2016/12/3
 * Time: 17:36
 */
@Service
public class RegisterManager extends BaseManager {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProjectMapperExt projectMapperExt;

    @Autowired
    private RegisterSuccessMapperExt registerSuccessMapperExt;

    @Autowired
    private ProjectExtensionRelationManager projectExtensionRelationManager;

    @Autowired
    private ProjectExtensionDicManager projectExtensionDicManager;

    @Autowired
    private AreaMapperExt areaMapperExt;

    @Autowired
    private AreaManager areaManager;

    @Autowired
    private SummaryBatchRelationMapperExt summaryBatchRelationMapperExt;

    @Autowired
    private CitizenBankMapperExt citizenBankMapperExt;

    @Autowired
    private CitizenBankManager citizenBankManager;

    @Autowired
    private ProjectExtensionDicMapperExt projectExtensionDicMapperExt;

    @Autowired
    private ProjectRegisterBatchMapperExt projectRegisterBatchMapperExt;

    @Autowired
    private ProjectRegisterBatchManager projectRegisterBatchManager;

    @Autowired
    private RegisterSuccessManager registerSuccessManager;

    @Autowired
    private RegisterFailManager registerFailManager;

    @Autowired
    private ProjectRegisterUploadManager projectRegisterUploadManager;

    @Autowired
    private CitizenInfoManager citizenInfoManager;

    @Autowired
    private ProjectExtensionDetailManager projectExtensionDetailManager;

    @Autowired
    private ProjectManager projectManager;

    @Autowired
    private OrgBatchSummaryManager orgBatchSummaryManager;

    @Autowired
    private PaySummaryManager paySummaryManager;

    @Autowired
    private SummaryBatchRelationManager summaryBatchRelationManager;

    @Autowired
    private CitizenInfoMapperExt citizenInfoMapperExt;

    @Autowired
    private HouseholdMapperExt householdMapperExt;

    @Autowired
    private DictionaryManager dictionaryManager;

    @Autowired
    private CitizenPropertyManager citizenPropertyManager;

    /**
     * 获取待上报人员列表
     *
     * @param searchDTO
     * @return
     */
    public List<RegisterTemplateDTO> needReportingList(RegisterTemplateSearchDTO search) {


        /*CitizenInfoSearchDTO citizenInfoSearchDTO = new CitizenInfoSearchDTO();
        citizenInfoSearchDTO.setAll(search.getAll());
        citizenInfoSearchDTO.setAreaId(search.getAreaId());
        citizenInfoSearchDTO.setName(search.getName());
        citizenInfoSearchDTO.setIdentNumber(search.getIdentNumber());
        citizenInfoSearchDTO.setMaster(search.getMaster());
        citizenInfoSearchDTO.setCitizenInfoIds(search.getCitizenInfoId());
        List<CitizenInfoDTO> citizenInfoList = citizenInfoManager.getCitizenInfoList(citizenInfoSearchDTO);
*/

        if (search.getName() == null) {
            search.setName("");
        }
        if (search.getIdentNumber() == null) {
            search.setIdentNumber("");
        }
        List<Integer> areaIds = new ArrayList<>();

        if (search.getAreaId() != null && search.getAreaId() > 0) {

            List<Integer> ids = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, search.getAreaId()));

            if (ids != null && ids.size() > 0) {
                ids.add(search.getAreaId());
                areaIds = ids;
            } else {
                areaIds.add(search.getAreaId());
            }
        }

        List<Integer> citizenIds = new ArrayList<>();
        if (!search.getAll()) {
            citizenIds = search.getCitizenInfoId();
        }
        citizenIds.add(0);
        Integer isAll = search.getAll() ? 1 : 0;
        Integer isMaster = -1;
        if (search.getMaster() != null)
            isMaster = search.getMaster() ? 1 : 0;

        List<RegisterTempateDTO> citizenInfoList = registerSuccessMapperExt.needReportingList(areaIds, search.getName(), search.getIdentNumber(), isMaster, isAll, citizenIds);

        //get extensions for project
        Project project = projectMapperExt.selectByPrimaryKey(search.getProjectId());
        List<ProjectExtensionRelation> extRelationList = projectExtensionRelationManager.getProjectExtensionRelationListByProjectId(search.getProjectId());
        List<String> extNames = new ArrayList<String>();
        if (extRelationList != null && extRelationList.size() > 0) {
            for (ProjectExtensionRelation extRelation : extRelationList) {
                Integer extId = extRelation.getExtId();
                ProjectExtensionDic projectExtension = projectExtensionDicMapperExt.selectByPrimaryKey(extId);
                if (projectExtension != null)
                    extNames.add(projectExtension.getExtName());
            }
        }

        //获取areaName
        Area area = areaMapperExt.selectByPrimaryKey(search.getAreaId());

        //银行map
        Map<String, String> bankMap = new HashMap<>();


        //combinating
        List<RegisterTemplateDTO> result = new ArrayList<RegisterTemplateDTO>();
        if (citizenInfoList != null && citizenInfoList.size() > 0) {
            for (RegisterTempateDTO citizenInfo : citizenInfoList) {
                RegisterTemplateDTO dto = new RegisterTemplateDTO();
                dto.setName(citizenInfo.getName());
                dto.setAreaId(citizenInfo.getAreaId());
                //get areaName
                dto.setAreaName(area.getAreaName());
                //get bank number
                /*List<CitizenBankDTO> citizenBankList = citizenBankManager.getByCitizenInfoId(citizenInfo.getCitizenInfoId());
                if (citizenBankList != null && citizenBankList.size() > 0)
                    dto.setBankNumber(citizenBankList.get(0).getBankNumber());
*/
                if (bankMap.containsKey(citizenInfo.getBankCode())) {
                    dto.setBankName(bankMap.get(citizenInfo.getBankCode()));
                } else {
                    DictionaryDTO dic = dictionaryManager.getDicByCodeAndTypeId(citizenInfo.getBankCode(), CommonConstant.DIC_TYPE_BANKCODE);
                    dto.setBankName(dic.getDictionaryName());
                    bankMap.put(dic.getDictionaryCode(), dic.getDictionaryName());
                }

                dto.setBankNumber(citizenInfo.getBankNumber());


                dto.setIdentNumber(citizenInfo.getIdentNumber());

                dto.setProjectName(project.getProjectName());
                dto.setProjectId(search.getProjectId());
                dto.setSubsidyCount(search.getSubsidyCount());
                dto.setYear(search.getYear());

                //add extensions
                dto.setExtNames(extNames);
                result.add(dto);
            }
        }
        return result;
    }


    /**
     * 上传
     *
     * @param header
     * @param data
     * @return
     */
    public BarDTO uploadCitizen(String[] header, List<RegisterTemplateDataDTO> data, Integer uploadRegisterType, Integer batchId) throws BusinessException, InterruptedException {
        //get condition for selecting batch
//        RegisterUploadResultDTO registerUploadResultDTO = new RegisterUploadResultDTO();
        log.info("header: " + JSONArray.fromObject(header).toString() + "  data: " + JSONArray.fromObject(data).toString());

        boolean isOrg = false;
        if (!"typein".equals(UserUtils.getUser().getUserType())) {
            isOrg = true;
        }


        Integer projectId = null, year = null, subsidyCount = null, areaId = null;
        String areaName = null, projectOrgCode = null, projectName = null, projectPayCycleCode = null, projectPayObjCode = null;
        Integer destBatchId = null;

        //获取项目相关信息，登记区划相关信息
        if (data != null && data.size() > 0) {
            RegisterTemplateDataDTO dto = data.get(0);
            if (dto != null) {

                //项目
                projectName = dto.getProjectName();
                ProjectSearchDTO projectSearchDTO = new ProjectSearchDTO();
                projectSearchDTO.setProjectName(projectName);
                List<ProjectDTO> projects = projectManager.all(projectSearchDTO);
                if (projects != null && projects.size() > 0) {
                    ProjectDTO projectDTO = projects.get(0);
                    projectId = projectDTO.getProjectId();
                    projectPayCycleCode = projectDTO.getPayCycleCode();
                    projectPayObjCode = projectDTO.getPayObjCode();
                    projectOrgCode = projectDTO.getOrgCode();
                } else {
                    throw new BusinessException(ValidatingRegisterTypeEn.projectNameNotFind.getMean(), ValidatingRegisterTypeEn.projectNameNotFind.getCode().toString());
                }

                year = dto.getYear();
                //校验发放次数
                subsidyCount = dto.getSubsidyCount();
                if (subsidyCount < 1 || subsidyCount > DicUtils.getPayCycle(projectPayCycleCode)) {
                    throw new BusinessException(ValidatingRegisterTypeEn.projectSbExceedMax.getMean(), ValidatingRegisterTypeEn.projectSbExceedMax.getCode().toString());
                }


                areaName = dto.getAreaName();  //登记区划

                //登记区划
                if (!isOrg && batchId == null) {
                    AreaSearchDTO areaSearchDTO = new AreaSearchDTO();
                    areaSearchDTO.setAreaName(areaName);
                    if (UserUtils.getUser() != null)
                        areaSearchDTO.setAreaParentId(UserUtils.getUser().getAreaId());
                    //areaSearchDTO.setAreaParentId(UserUtils.getUser().getAreaId());
                    List<AreaDTO> areas = areaManager.all(areaSearchDTO);
                    if (areas != null && areas.size() > 0) {
                        areaId = areas.get(0).getAreaId();  //登记区划id
                    } else {
                        throw new BusinessException(ValidatingRegisterTypeEn.areaNotFind.getMean(), ValidatingRegisterTypeEn.areaNotFind.getCode().toString());
                    }
                }
            }
        }

        //获取扩展属性列id，并进行校验是否存在
        Integer[] extId = new Integer[0];
        if (header != null) {
            extId = new Integer[header.length];
            for (int i = 0; i < header.length; i++) {
                extId[i] = 0;
                String extName = header[i];
                ProjectExtensionDicSearchDTO projectExtensionDicSearchDTO = new ProjectExtensionDicSearchDTO();
                projectExtensionDicSearchDTO.setExtName(extName);
                List<ProjectExtensionDicDTO> extList = projectExtensionDicManager.all(projectExtensionDicSearchDTO);
                if (extList != null && extList.size() > 0) {
                    extId[i] = extList.get(0).getExtId();
                } else {
                    throw new BusinessException(String.format(ValidatingRegisterTypeEn.missExtProName.getMean(), extName), ValidatingRegisterTypeEn.missExtProName.getCode().toString());
                }
            }
        }


        //如果是主管部门登记，则登记区划为主管部门所在的区划（区县）
        if (isOrg) {
            areaId = UserUtils.getUser().getAreaId();
            areaName = UserUtils.getUser().getAreaName();
        }

        //创建登记批次 project_register_batch

        ProjectRegisterBatchExample batchExample = new ProjectRegisterBatchExample();
        ProjectRegisterBatchExample.Criteria batchCriteria = batchExample.createCriteria();
        if (batchId == null) {
            if (projectId != null && projectId > 0) {
                batchCriteria.andProjectIdEqualTo(projectId);
            }
            if (year != null && year > 0) {
                batchCriteria.andYearEqualTo(year);
            }
            if (areaId != null && areaId > 0) {
                batchCriteria.andAreaIdEqualTo(areaId);
            }
            if (subsidyCount != null && subsidyCount > 0) {
                batchCriteria.andSubsidyCountEqualTo(subsidyCount);
            }
            batchCriteria.andStateNotIn(ProjectRegisterBatchEn.getOverStateList());
        } else {
            batchCriteria.andBatchIdEqualTo(batchId);
        }

        batchCriteria.andIsDeleteEqualTo(Boolean.FALSE);
        List<ProjectRegisterBatch> batchList = projectRegisterBatchMapperExt.selectByExample(batchExample);
        if (batchList != null && batchList.size() > 0) { //exists
            destBatchId = batchList.get(0).getBatchId();

            boolean r = false;
            if (!isOrg) {
                if (!batchList.get(0).getState().equals(ProjectRegisterBatchEn.register_ing.getCode())) {
                    r = true;
                }
            } else {
                if (!batchList.get(0).getState().equals(ProjectRegisterBatchEn.org_auditor_ing.getCode())) {
                    r = true;
                }
            }
            if (r) {
                throw new BusinessException(String.format(ValidatingRegisterTypeEn.hasRuningBatch.getMean(), batchList.get(0).getYear(), batchList.get(0).getSubsidyCount()), ValidatingRegisterTypeEn.hasRuningBatch.getCode().toString());
            }

        } else {
            //insert new batch
            ProjectRegisterBatch record = new ProjectRegisterBatch();
            record.setAreaId(areaId);  //登记区划id
            record.setAreaName(areaName);  //登记区划名
            record.setCreateTime(DateUtil.getCurrentTime());

            record.setProjectId(projectId);
            record.setProjectName(projectName);
            record.setYear(year);
            record.setPayCycleCode(projectPayCycleCode);
            record.setPayObjCode(projectPayObjCode);
            record.setSubsidyCount(subsidyCount);
            if (UserUtils.getUser() != null) {
                record.setCreatorUserType(UserUtils.getUser().getUserType());
                record.setCreatorAreaId(UserUtils.getUser().getAreaId());
                record.setCreator(UserUtils.getUser().getUserName());
            }
            if (!isOrg) {
                //乡镇
                record.setState(ProjectRegisterBatchEn.register_ing.getCode());
            } else {
                //主管部门
                record.setState(ProjectRegisterBatchEn.org_auditor_ing.getCode());
            }
            record.setCreateTime(DateUtil.getCurrentTime());
            projectRegisterBatchMapperExt.insertSelective(record);
            destBatchId = record.getBatchId();
            log.info("ppp:" + destBatchId);
        }


        //deal project_register_upload
        ProjectRegisterUploadDTO uploadDto = new ProjectRegisterUploadDTO();
        uploadDto.setProjectId(projectId);
        uploadDto.setYear(year);
        uploadDto.setBatchId(destBatchId);
        ProjectRegisterUploadDTO uploadResultDto = projectRegisterUploadManager.save(uploadDto);


        //begin 多线程化 begin
        /*
        * 一个大任务对应一个进度管理DTO，
        * */
        //validating and updating
        BarDTO barDTO = new BarDTO();
        if (data != null && data.size() > 0) {

            String barId = String.format(CommonConstant.KEY_BAR_UPLOAD_REGISTER_ID, uploadResultDto.getUploadId().toString());
            barDTO = new BarDTO(barId, UploadTypeEn.register.getCode(), data.size());

            int index = 1;
            List<RegisterTemplateDataDTO> templateDataDTOList = new ArrayList<>();

            for (int i = 0; i < data.size(); i++) {

                RegisterTemplateDataDTO temp = data.get(i);
                temp.setProjectId(projectId);
                temp.setAreaId(areaId);
                temp.setAreaName(areaName);
                temp.setRegisterAreaName(areaName);
                templateDataDTOList.add(temp);

                if (index % 100 == 0 || index == data.size()) {
                    //每100个数一个线程，来执行；或者循环到列表结尾，将剩下的数量交给最后一个线程来执行
                    RegisterUploadThread registerUploadThread = new RegisterUploadThread();

                    registerUploadThread.setBarDTO(barDTO);

                    registerUploadThread.setHeader(header);
                    registerUploadThread.setData(templateDataDTOList);
                    registerUploadThread.setProjectId(projectId);
                    registerUploadThread.setDestBatchId(destBatchId);
                    registerUploadThread.setProjectPayCycleCode(projectPayCycleCode);
                    registerUploadThread.setProjectOrgCode(projectOrgCode);
                    registerUploadThread.setUploadId(uploadResultDto.getUploadId());
                    registerUploadThread.setYear(year);
                    registerUploadThread.setExtId(extId);

                    registerUploadThread.setCacheService(cacheService);
                    registerUploadThread.setCitizenInfoMapperExt(citizenInfoMapperExt);
                    registerUploadThread.setProjectExtensionDetailManager(projectExtensionDetailManager);
                    registerUploadThread.setCitizenBankManager(citizenBankManager);
                    registerUploadThread.setCitizenBankMapperExt(citizenBankMapperExt);
                    registerUploadThread.setRegisterFailManager(registerFailManager);
                    registerUploadThread.setRegisterSuccessManager(registerSuccessManager);
                    registerUploadThread.setRegisterSuccessMapperExt(registerSuccessMapperExt);
                    registerUploadThread.setHouseholdMapperExt(householdMapperExt);
                    registerUploadThread.setCitizenInfoManager(citizenInfoManager);
                    registerUploadThread.setProjectRegisterUploadManager(projectRegisterUploadManager);
                    registerUploadThread.setProjectRegisterBatchMapperExt(projectRegisterBatchMapperExt);
                    registerUploadThread.setCitizenPropertyManager(citizenPropertyManager);

                    registerUploadThread.setUsersDTO(UserUtils.getUser());

                    String threadName = "RegisterUploadThread-" + System.currentTimeMillis();

                    registerUploadThread.setThreadName(threadName);

                    Thread thread = new Thread(registerUploadThread, threadName);
                    thread.start();

                    logger.info(threadName + " started, size " + templateDataDTOList.size());

                    Thread.sleep(100L);

                    templateDataDTOList = new ArrayList<>();
                }
                index++;
            }
        } else {
            throw new BusinessException(ValidatingRegisterTypeEn.execlNoRecord.getMean(), ValidatingRegisterTypeEn.execlNoRecord.getCode().toString());
        }

        //begin 多线程化 end
        return barDTO;
    }

    /**
     * 财政对批次汇总生成代发文件
     *
     * @param searchDTO
     * @return
     */
    public SummaryFileDTO financeCreatedFile(String summaryId) {
        SummaryFileDTO result = new SummaryFileDTO();
        List<RegisterSuccessDTO> subList = new ArrayList<RegisterSuccessDTO>();
        SummaryDTO summaryDTO = new SummaryDTO();
        String projectName = null;
        Integer totalCount = 0;
        BigDecimal totalMoney = new BigDecimal(0.00);
        totalMoney.setScale(2, BigDecimal.ROUND_HALF_UP);


        //get org_batch_summary
        OrgBatchSummaryDTO orgBatchSummaryDTO = orgBatchSummaryManager.get(summaryId);
        summaryDTO.setSummaryId(summaryId);
        if (orgBatchSummaryDTO != null) {
            summaryDTO.setRegisterArea(areaMapperExt.selectByPrimaryKey(orgBatchSummaryDTO.getAreaId()).getAreaName());
        }


        List<RegisterSuccessDTO> list = registerSuccessManager.getRegisterSuccessListForCreateFile(summaryId, ProjectRegisterEn.getSuccessStateList());

        Map<Integer, String> areaNameMap = new HashMap<>();

        if (list != null && list.size() > 0) {

            String tempBankcode = "", tempBankName = "";

            for (int i = 0; i < list.size(); i++) {
                RegisterSuccessDTO item = list.get(i);
                item.setIndex(i + 1);

                totalCount++;

                //System.out.println(item.getSubsidyMoney().toString());

                totalMoney = MathUtil.plus(totalMoney, item.getSubsidyMoney());

                //登记人员所属的区划名
                Integer areaId = item.getAreaId();
                if (areaId != null && areaId > 0) {
                    if (areaNameMap.containsKey(areaId)) {

                    } else {
                        AreaDTO areaDTO = areaManager.get(areaId);
                        if (areaDTO != null) {
                            areaNameMap.put(areaId, areaDTO.getAreaName());
                        }
                    }
                    item.setAreaName(areaNameMap.get(areaId));
                }

                //登记人员的银行卡名称
                if (item.getBankCode().equals(tempBankcode)) {
                    item.setBankName(tempBankName);
                } else {
                    DictionaryDTO dic = (DictionaryDTO) cacheService.getCache(String.format(CommonConstant.KEY_DIC, CommonConstant.DIC_TYPE_BANKCODE, item.getBankCode()));
                    item.setBankName(dic.getDictionaryName());
                    tempBankcode = dic.getDictionaryCode();
                    tempBankName = dic.getDictionaryName();
                }

                //登记项目的项目名称
                if (projectName == null) {
                    ProjectSearchDTO projectSearchDTO = new ProjectSearchDTO();
                    projectSearchDTO.setProjectId(item.getProjectId());
                    List<ProjectDTO> projects = projectManager.all(projectSearchDTO);
                    if (projects != null && projects.size() > 0) {
                        projectName = projects.get(0).getProjectName();
                        summaryDTO.setProjectName(projectName);
                    }
                    summaryDTO.setSubsidyCount(item.getSubsidyCount());
                    summaryDTO.setYear(item.getYear());

                }
            }
        }
        summaryDTO.setSummaryId(summaryId);
        summaryDTO.setTotalCount(totalCount);
        totalMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
        summaryDTO.setTotalMoney(totalMoney);

        subList.addAll(list);
        //result.setList(subList);
        result.setSummaryDTO(summaryDTO);

        try {
            cacheService.putCache(String.format(CommonConstant.KEY_FINANCE_CREATE_DATA, summaryId), subList, 60 * 1); //60秒
        } catch (Exception ex) {
            log.error("put " + String.format(CommonConstant.KEY_FINANCE_CREATE_DATA, summaryId) + " to redis error, count=" + subList.size());
        }

        //修改状态


        return result;
    }

    /**
     * upload callback for bank
     *
     * @param summaryDTO
     * @param detailList
     * @return
     */
    public Boolean updateSummaryState(int phase, String summaryId, String url) {

        OrgBatchSummaryDTO orgBatchSummaryDTO = orgBatchSummaryManager.get(summaryId);

        if (!ProjectRegisterBatchEn.isOver(orgBatchSummaryDTO.getState())) {

            //insert or update pay summary
            List<PaySummaryDTO> paySummaryList = paySummaryManager.all(summaryId);
            if (paySummaryList != null && paySummaryList.size() > 0) {
                //存在记录，则更新

                PaySummaryDTO dto = paySummaryList.get(0);
                if (phase == CommonConstant.SUMMARY_PHASE_DOWNLOAD) {
                    if (UserUtils.getUser() != null) {
                        dto.setDataDownloader(UserUtils.getUser().getUserName());
                    }
                    dto.setDataDownloadTime(DateUtil.getCurrentTime());
                } else if (phase == CommonConstant.SUMMARY_PHASE_CREATE) {
                    Integer totalCount = 0;
                    BigDecimal totalMoney = new BigDecimal(0.00);
                    String payCycleCode = null;
                    //OrgBatchSummaryDTO orgBatchSummaryDTO = orgBatchSummaryManager.get(summaryId);
                    if (orgBatchSummaryDTO != null) {
                        totalCount = orgBatchSummaryDTO.getSuccessCount();
                        totalMoney = orgBatchSummaryDTO.getSuccessMoney();
                        payCycleCode = orgBatchSummaryDTO.getPayCycleCode();
                    }
                    dto.setCreator(UserUtils.getUser().getUserName());
                    if (url != null)
                        dto.setPayFileName(url);
                    dto.setPayCycleCode(payCycleCode);
                    dto.setPayMoney(totalMoney);
                    dto.setPeopleCount(totalCount);
                }
                paySummaryManager.save(dto);

            } else {
                Integer totalCount = 0;
                BigDecimal totalMoney = new BigDecimal(0.00);
                String payCycleCode = null;
                //OrgBatchSummaryDTO orgBatchSummaryDTO = orgBatchSummaryManager.get(summaryId);
                if (orgBatchSummaryDTO != null) {
                    totalCount = orgBatchSummaryDTO.getSuccessCount();
                    totalMoney = orgBatchSummaryDTO.getSuccessMoney();
                    payCycleCode = orgBatchSummaryDTO.getPayCycleCode();
                }
                PaySummaryDTO dto = new PaySummaryDTO();
                dto.setSummaryId(summaryId);
                if (UserUtils.getUser() != null) {
                    dto.setCreator(UserUtils.getUser().getUserName());
                }
                if (url != null)
                    dto.setPayFileName(url);
                dto.setPayCycleCode(payCycleCode);
                dto.setPayMoney(totalMoney);
                dto.setPeopleCount(totalCount);

                paySummaryManager.save(dto);
            }

            //修改register_success表summaryId对应的登记人员记录为finance_created_file(110, "已生成代发文件，待下载")
            if (phase == CommonConstant.SUMMARY_PHASE_CREATE || phase == CommonConstant.SUMMARY_PHASE_DOWNLOAD) {

                RegisterSuccess update = new RegisterSuccess();
                ProjectRegisterBatch update2 = new ProjectRegisterBatch();

                if (phase == CommonConstant.SUMMARY_PHASE_CREATE) {
                    update.setState(ProjectRegisterEn.finance_created_file.getCode());
                    orgBatchSummaryDTO.setState(ProjectRegisterBatchEn.finance_created_file.getCode());
                    update2.setState(ProjectRegisterBatchEn.finance_created_file.getCode());

                } else {
                    update.setState(ProjectRegisterEn.finance_downloaded_file.getCode());
                    orgBatchSummaryDTO.setState(ProjectRegisterBatchEn.finance_downloaded_file.getCode());
                    update2.setState(ProjectRegisterBatchEn.finance_downloaded_file.getCode());

                }
                update.setModifyTime(DateUtil.getCurrentTime());
                update2.setModifyTime(DateUtil.getCurrentTime());

                //更新 register_success
                RegisterSuccessExample example = new RegisterSuccessExample();
                RegisterSuccessExample.Criteria criteria = example.createCriteria();
                criteria.andSummaryIdEqualTo(summaryId);
                criteria.andStateIn(ProjectRegisterEn.getSuccessStateList());
                registerSuccessMapperExt.updateByExampleSelective(update, example);

                //更新 org_batch_summary
                orgBatchSummaryManager.save(orgBatchSummaryDTO);

                //更新 project_register_batch
                ProjectRegisterBatchExample example2 = new ProjectRegisterBatchExample();
                ProjectRegisterBatchExample.Criteria criteria2 = example2.createCriteria();
                criteria2.andBatchIdIn(orgBatchSummaryManager.selectBatchIdsBySummaryId(summaryId));
                criteria2.andIsDeleteEqualTo(false);
                projectRegisterBatchMapperExt.updateByExampleSelective(update2, example2);

            } else { //SUMMARY_PHASE_BANKUPLOAD


            }

        }
        return Boolean.TRUE;
    }


    //上传银行回执
    public BarDTO financeUploadReceipt(String summaryId, List<SummaryDetailDTO> detailList) throws BusinessException {
        BarDTO barDTO = new BarDTO();
        if (detailList != null && detailList.size() > 0) {

            LinkedBlockingQueue<SummaryDetailDTO> queue = new LinkedBlockingQueue<>();

            for (SummaryDetailDTO dto : detailList) {
                try {
                    queue.put(dto);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            String barId = String.format(CommonConstant.KEY_BAR_UPLOAD_BANK_RETURN_ID, summaryId);
            barDTO = new BarDTO(barId, UploadTypeEn.bank_return.getCode(), queue.size());

            int number = 0;
            while (number < CommonConstant.THREAD_NUMBER_UPLOAD_BANK_RETURN) {
                if (queue.size() < CommonConstant.THREAD_MAX_RECORD_COUNT) {
                    number = CommonConstant.THREAD_NUMBER_UPLOAD_BANK_RETURN;
                }
                number++;
                String threadName = "BankReturnUploadThread-" + summaryId + "-" + number;

                BankReturnUploadThread bankReturnUploadThread = new BankReturnUploadThread();
                bankReturnUploadThread.setRegisterSuccessManager(registerSuccessManager);
                bankReturnUploadThread.setSummaryId(summaryId);
                bankReturnUploadThread.setQueue(queue);
                bankReturnUploadThread.setBarDTO(barDTO);
                bankReturnUploadThread.setThreadName(threadName);
                bankReturnUploadThread.setUsersDTO(UserUtils.getUser());

                Thread thread = new Thread(bankReturnUploadThread, threadName);
                thread.start();
            }

//            UsersDTO usersDTO = UserUtils.getUser();
/*
            //创建一个新的线程，来监控回执上传是否已经完成
            new Thread(new Runnable() {
                @Override
                public void run() {
                    BarDTO bar;
                    do {
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Integer bankCallBackState = 0;
                        bar = (BarDTO) cacheService.getCache(barId);
                        if (bar == null) break;
                        if (bar.getOver()) {
                            //任务已经结束

                            //更新 pay_summary
                            List<PaySummaryDTO> paySummaryList = paySummaryManager.all(summaryId);
                            if (paySummaryList != null && paySummaryList.size() > 0) {
                                for (PaySummaryDTO dto : paySummaryList) {
                                    if (usersDTO != null && usersDTO.getUserId() > 0) {
                                        dto.setRecUploader(usersDTO.getUserName());
                                        dto.setRecUploadTime(DateUtil.getCurrentTime());
                                        paySummaryManager.save(dto);
                                    }
                                }
                            }

                            *//*更新状态*//*
                            if (bar.getSuccess() > 0) {
                                if (bar.getFail() > 0) {
                                    bankCallBackState = ProjectRegisterBatchEn.bank_success_part.getCode();
                                } else {
                                    bankCallBackState = ProjectRegisterBatchEn.bank_success_all.getCode();
                                }
                            } else {
                                bankCallBackState = ProjectRegisterBatchEn.bank_fail_all.getCode();
                            }

                            //更新 org_batch_summary

                            OrgBatchSummaryDTO orgBatchSummaryDTO = orgBatchSummaryManager.get(summaryId);
                            orgBatchSummaryDTO.setState(bankCallBackState);
                            orgBatchSummaryManager.save(orgBatchSummaryDTO);

                            //更新 project_register_batch
                            ProjectRegisterBatch update = new ProjectRegisterBatch();
                            ProjectRegisterBatchExample example = new ProjectRegisterBatchExample();
                            ProjectRegisterBatchExample.Criteria criteria = example.createCriteria();
                            criteria.andBatchIdIn(orgBatchSummaryManager.selectBatchIdsBySummaryId(summaryId));
                            criteria.andIsDeleteEqualTo(false);
                            update.setState(bankCallBackState);
                            update.setModifyTime(DateUtil.getCurrentTime());
                            projectRegisterBatchMapperExt.updateByExampleSelective(update, example);

                        }

                    } while (!bar.getOver());
                }
            }, "monitor-bank-return-isfinish-" + System.currentTimeMillis()).start();
        */

        } else {
            throw new BusinessException("execl记录为空");
        }


        return barDTO;
    }


}
